package my.mall.admin.api.controller

import com.aliyun.oss.OSS
import com.aliyun.oss.OSSClient
import com.aliyun.oss.model.MatchMode
import com.aliyun.oss.model.PolicyConditions
import my.mall.common.enums.RespMetaEnum
import my.mall.common.pojo.CommonResp
import my.mall.common.util.DateUtils
import my.mall.common.util.RespUtils
import org.springframework.beans.factory.annotation.Value
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.*
import java.util.concurrent.TimeUnit

@RestController
@RequestMapping("file")
class FileController(
    private val ossClient: OSS,
    @Value("\${oss.access-key}")
    private val accessKey: String,
    @Value("\${oss.bucket}")
    private val bucket: String
) {

    @PostMapping("/upload")
    fun fileUpload(@RequestParam("file") file: MultipartFile): CommonResp<*> {
        // 判断文件是否为空
        if (!file.isEmpty) {
            val fileNameArr = StringUtils.split(file.originalFilename, ".")
                ?: return RespUtils.warning<Any>(RespMetaEnum.PARAM_ERROR)
            // 文件保存路径
            val filePath = UUID.randomUUID().toString().replace("-", "") + "." + fileNameArr[fileNameArr.size - 1]
            // 转存文件
            file.transferTo(File("c:\\workspace\\$filePath"))
            return RespUtils.success(filePath)
        }
        return RespUtils.warning<Any>(RespMetaEnum.TIMEOUT)
    }

    @GetMapping("policy")
    fun getOssPolicy(@RequestParam("suffix") suffix: String): CommonResp<Map<String, Any>> {
        val fullName = DateUtils.formatLocalDate(LocalDate.now()) + "/" +
                UUID.randomUUID().toString().replace("-", "") + "." + suffix.split(".").last()
        val conditions = PolicyConditions()
        conditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000)
        conditions.addConditionItem(MatchMode.Exact, PolicyConditions.COND_KEY, fullName)
        val expiredTime = LocalDateTime.now().plusMinutes(10)
        val policy =
            ossClient.generatePostPolicy(DateUtils.asDate(expiredTime), conditions)
        val signature = ossClient.calculatePostSignature(policy)
        val response = LinkedHashMap<String, Any>()
        response["accessId"] = accessKey
        response["policy"] = String(Base64.getEncoder().encode(policy.toString().toByteArray()))
        response["signature"] = signature
        response["dir"] = fullName
        response["host"] = "https://$bucket.oss-cn-hangzhou.aliyuncs.com"
        response["expire"] = TimeUnit.SECONDS.toSeconds(expiredTime.toEpochSecond(ZoneOffset.UTC))
        return RespUtils.success(response)
    }

}